package com.veal98.tree;

import com.veal98.bean.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class MinimumAbsoluteDifferenceInBst_530 {

    public int getMinimumDifference(TreeNode root) {
        if (root == null) {
            return 0;
        }

        // 辅助栈
        Stack<TreeNode> stack = new Stack<>();
        // 工作节点
        TreeNode cur = root;
        // 存储中序遍历的结果
        List<Integer> list = new ArrayList<>();

        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                // 左
                cur = cur.left;
            } else {
                // 根
                cur = stack.pop();
                list.add(cur.val);
                // 右
                cur = cur.right;
            }
        }

        // 遍历中序遍历结果，找到最小差值
        int res = Integer.MAX_VALUE;
        for (int i = 1; i < list.size(); i ++) {
            res = Math.min(list.get(i) - list.get(i - 1), res);
        }

        return res;
    }

    public int getMinimumDifference2(TreeNode root) {
        if (root == null) {
            return 0;
        }

        // 辅助栈
        Stack<TreeNode> stack = new Stack<>();
        // 工作节点
        TreeNode cur = root;
        // 中序遍历的前驱节点
        TreeNode pre = null;
        // 最小差值
        int res = Integer.MAX_VALUE;


        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                // 左
                cur = cur.left;
            } else {
                // 根
                cur = stack.pop();

                if (pre != null) {
                    res = Math.min(cur.val - pre.val, res);
                }
                pre = cur;

                // 右
                cur = cur.right;
            }
        }

        return res;
    }



}
